class Image {
  constructor($, options) {
    this.$dom = $(options.dom);
    this.itemImg = this.$dom.children(".imgC").children(".itemImg");
    this.indicatorItem = this.$dom
      .children(".car-indicator")
      .children(".indicator-item");
    this.speed = options.speed;
    this.curIdx = 0;
    this.timer = null;
    this.init();
  }
  init() {
    this.autoPlay();
    this.bindEvent();
  }

  bindEvent() {
    this.$dom.on("mouseover", { event: "in" }, $.proxy(this.mousemove, this));
    this.$dom.on("mouseout", { event: "out" }, $.proxy(this.mousemove, this));
    this.$dom.on("click", $.proxy(this.indicatorClick, this));
  }
  indicatorClick(ev) {
    const e = ev || window.srcElement,
      tar = e.target || e.srcElement,
      tagName = tar.tagName.toLowerCase();
    if (tagName === "button") {
      const dir = tar.dataset.dir;
      this.changeCurIdx(dir);
      this._pageChange(this.curIdx);
    } else if (tagName === "i") {
      this.curIdx = $(tar).index();
      this._pageChange(this.curIdx);
    }
  }
  mousemove(e) {
    const event = e.data.event;
    switch (event) {
      case "in":
        clearInterval(this.timer);
        break;
      case "out":
        this.autoPlay();
        break;
      default:
        break;
    }
  }
  autoPlay() {
    this.timer = setInterval($.proxy(this.run, this), this.speed);
  }
  run() {
    this.changeCurIdx("next");
    this._pageChange(this.curIdx);
  }
  changeCurIdx(dir) {
    switch (dir) {
      case "next":
        this.curIdx === this.itemImg.length - 1
          ? (this.curIdx = 0)
          : this.curIdx++;
        break;
      case "prev":
        this.curIdx === 0
          ? (this.curIdx = this.itemImg.length - 1)
          : this.curIdx--;
        break;
      default:
        break;
    }
  }
  _pageChange(index) {
    this.itemImg
      .eq(index)
      .addClass("active")
      .siblings(".itemImg")
      .removeClass("active");
    this.indicatorItem
      .eq(index)
      .addClass("active")
      .siblings(".indicator-item")
      .removeClass("active");
  }
}

export { Image };
